package algorithm_demo.demo02;

/**
 * 二叉树，查找二叉树的某个节点，返回该节点的后继节点
 *
 * 中序遍历
 * 左->头->右 的顺序
 * 如果一个节点？左树上的最右节点X,则?就是X的后继节点
 *
 * @author Api
 * @date 2023/2/11 21:00
 */
public class Code04_BinaryTreeSuccessorNode {

    public static class Node{
        public int value;
        public Node left;
        public Node right;
        public Node parent;
    }

    public static Node getSuccessorNode(Node node){
        if (node == null){
            return null;
        }
        if (node.right != null){
            return getLeftMost(node.right);
        }else{//无右子树
            Node parent = node.parent;
            while(parent != null && parent.left != node){//当前节点是其父亲节点右孩子，或者修改为parent.right==node
                node = parent;
                parent = node.parent;
            }
            return parent;
        }
    }

    public static Node getLeftMost(Node node){
        if (node == null){
            return node;
        }
        while(node.left != null){
            node = node.left;
        }
        return node;
    }
}
